package com.link.base.base.sms.controller;

import com.alibaba.fastjson.JSON;
import com.link.base.base.sms.model.PushSms;
import com.link.base.base.sms.model.TempSmsAssem;
import com.link.base.sms.model.SmsSend;
import com.link.base.sms.model.Template;
import com.link.base.user.model.CoreUser;
import com.link.base.base.sms.model.MsgTemplate;
import com.link.base.base.sms.service.TemplateService;
import com.link.base.base.user.service.UserService;
import com.link.base.wechat.wxmessage.model.WxTemplateMsg;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.PropertyUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author: liulu
 * @Date:15:37 2018/11/5
 */
@Controller
@RequestMapping("/link/template")
public class TemplateController extends BasicController<Template> {

    @Resource
    private TemplateService templateService;

    @Resource
    private UserService userService;



    @Override
    public BasicService<Template> getBasicService() throws Exception {
        return templateService;
    }


    /**
     * 更新前做操作,模板内容长度加上模板内参数长度不大于900
     * @author 朱泊阳
     * @date 2019/4/15 16:08
     */
    @Override
    public void beforUpdate(Template entity, HttpServletRequest request) throws Exception {
        int count = entity.getText().length()
                + (StringUtils.isBlank(entity.getParameter1()) ? 0 : entity.getParameter1().length())
                + (StringUtils.isBlank(entity.getParameter2()) ? 0 : entity.getParameter2().length())
                + (StringUtils.isBlank(entity.getParameter3()) ? 0 : entity.getParameter3().length())
                + (StringUtils.isBlank(entity.getParameter4()) ? 0 : entity.getParameter4().length())
                + (StringUtils.isBlank(entity.getParameter5()) ? 0 : entity.getParameter5().length())
                + (StringUtils.isBlank(entity.getParameter6()) ? 0 : entity.getParameter6().length())
                + (StringUtils.isBlank(entity.getParameter7()) ? 0 : entity.getParameter7().length())
                + (StringUtils.isBlank(entity.getParameter8()) ? 0 : entity.getParameter8().length())
                + (StringUtils.isBlank(entity.getParameter9()) ? 0 : entity.getParameter9().length())
                + (StringUtils.isBlank(entity.getParameter10()) ? 0 : entity.getParameter10().length());
        int countNum = 900;
        if (count > countNum) {
            throw new ServiceException("SMS-006", (count / 2) + "");
        }

    }

    /**
     * 获取是否开启短信模板是否同步腾讯云
     *
     * @author 朱义鹏
     * @date 2019/4/15 16:08
     */
    @RequestMapping(value = "/getSmsSynToTencent")
    @ResponseBody
    public Map<String, Object> getSmsSynToTencent() {
        Map<String, Object> result = new HashMap<>(16);
        try {
            CoreUser loginUser = UserUtil.getUser();
            String smsSynToTencent = PropertyUtil.getProperty("smsSynToTencent", loginUser.getLoginCorpId());
            result.put("success", true);
            result.put("smsSynToTencent", smsSynToTencent);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "获取短信模板是否同步腾讯云失败");
        }
        return result;
    }

    /**
     * 更新微信模板消息
     *
     * @author 朱泊阳
     * @date   2019/9/5 11:38
     */
    @RequestMapping(value = "upsertWxTemplate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsertWxTemplate(@RequestBody Template template) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            System.err.println(JSON.toJSONString(template));
            templateService.upsert(template);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 查询微信模板消息
     *
     * @author 朱泊阳
     * @date   2019/9/5 11:38
     */
    @RequestMapping(value = "queryWxTemplate")
    @ResponseBody
    public Map<String, Object> queryWxTemplate(@JsonParam Template entity, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            Template template = templateService.queryById(entity.getId());
            result.put("template", template);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 会员模块发送消息
     *
     * @author 汪大伟
     * @date   2019/9/5 11:38
     */
    @RequestMapping(value = "transWxTemplate")
    @ResponseBody
    public Map<String, Object> transWxTemplate(@RequestBody MsgTemplate msgTemplate) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            templateService.transWxTemplate(msgTemplate);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e);
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 处理消息根据短信模板发送短信
     *
     * @author zhuboyang
     * @date   2019/10/11 19:42
     */
    @RequestMapping(value = "/sendTmpSms")
    @ResponseBody
    public Map<String, Object> sendTmpSms(@RequestBody TempSmsAssem tempSmsAssem) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            Map<String, String> map = tempSmsAssem.getObjectMap();
            PushSms pushSms = new PushSms();
            //模板消息id
            pushSms.setTemId(tempSmsAssem.getTempSmsId());
            //短信签名
            pushSms.setSignatureId(tempSmsAssem.getTempSmsSignatureId());
            //匹配模板内对应的对象值发送短信
            SmsSend smsSend = templateService.sendTmpSms(null, pushSms, tempSmsAssem.getPhoneList(), map);
            //返回发送的参数
            tempSmsAssem.setTemparameter(smsSend.getTemparameter());
            //返回发送短信结果
            tempSmsAssem.setSendResult(smsSend.getSendState());
            result.put("success", true);
            result.put("result", tempSmsAssem);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 奖项发送微信消息
     *
     * @author 宁蓝昊
     * @date 2019-05-22 18:00
     */
    @RequestMapping(value = "/sendTempMsgForAct")
    @ResponseBody
    public Map<String, Object> sendTempMsgForAct(@RequestBody WxTemplateMsg templateMsg) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            templateService.sendTempMsgForAct(Long.valueOf(templateMsg.getAttr1()),
                Long.valueOf(templateMsg.getTemplateId()),
                templateMsg.getAttr2(),
                templateMsg.getTouser(),
                templateMsg.getAttr3());
            result.put("success", true);
            result.put("result", null);
            return result;
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "获取模板消息数据失败：" + e);
        }
        return result;
    }

}
